import { Button, Space, Tag } from 'ant-design-vue'
import { omit, omitBy } from 'lodash-unified'
import { defineComponent, ref } from 'vue'

import { loginLogApi } from '@/apis'
import { ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { TableOptions, useDialog, usePageHeight, useTableRef } from '@/hooks'
import { download } from '@/utils'

export default defineComponent({
  name: 'LoginLogView',
  setup() {
    const selectedIds = ref(new Set<string>())
    const tableConfig = ref({
      showOverflow: true,
      border: true,
      loading: false,
      height: 'auto',
      toolbarConfig: {
        custom: true,
        refresh: true,
        zoom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      formConfig: {
        items: [
          {
            field: 'userName',
            title: '用户名称',
            itemRender: {
              name: TABLE_ITEM_RENDER.AInput,
              props: {
                placeholder: '请输入用户名称'
              }
            }
          },
          {
            field: 'status',
            title: '状态',
            itemRender: {
              name: TABLE_ITEM_RENDER.ASelect,
              props: {
                placeholder: '登录状态'
              },
              options: [
                {
                  label: '成功',
                  value: '0'
                },
                {
                  label: '失败',
                  value: '1'
                }
              ]
            }
          },
          {
            field: 'loginDate',
            title: '登录时间',
            itemRender: {
              name: TABLE_RENDERER.FormItemDate,
              props: {
                type: 'range',
                placeholder: ['开始时间', '结束时间'],
                valueFormat: 'YYYY-MM-DD',
                keys: ['beginDate', 'endDate']
              }
            }
          },
          {
            itemRender: {
              name: TABLE_RENDERER.FormItemBtns
            }
          }
        ]
      },
      columns: [
        { type: 'checkbox', width: 50 },
        {
          field: 'infoId',
          title: '访问编号'
        },
        {
          field: 'userName',
          title: '用户名称'
        },
        {
          field: 'loginIp',
          title: '登录地址'
        },
        {
          field: 'loginLocation',
          title: '登录地点'
        },
        {
          field: 'browser',
          title: '浏览器'
        },
        {
          field: 'os',
          title: '操作系统'
        },
        {
          title: '登录状态',
          slots: {
            default: 'status'
          }
        },
        {
          field: 'msg',
          title: '操作信息'
        },
        {
          field: 'loginDate',
          title: '登录日期',
          minWidth: 100,
          formatter: TABLE_FORMAT.Date
        }
      ],
      pagerConfig: {
        pageSize: 15
      },
      proxyConfig: {
        seq: true,
        form: true,
        props: {
          result: 'list',
          total: 'total'
        },
        ajax: {
          query: async ({ page, form }) => {
            form = processingData(form)

            const data = await loginLogApi.getLoginLogPage({
              pageSize: page.pageSize,
              pageNum: page.currentPage,
              ...form
            })
            return data
          }
        }
      },
      onCheckboxChange({ checked, row }) {
        checked
          ? selectedIds.value.add(row.infoId)
          : selectedIds.value.delete(row.infoId)
      }
    } as TableOptions)

    const { tableRef, ...tableRefRestHook } = useTableRef(tableConfig)
    const { showConfirm } = useDialog()
    const { pageHeightPx } = usePageHeight()

    function processingData(data: any) {
      data = omit(data, ['loginDate'])
      data = omitBy(data, value => {
        return value === null
      })

      return data
    }

    function handleDel() {
      showConfirm({
        content: '确认删除？',
        onOk: async () => {
          await loginLogApi.deleteLoginLog({
            ids: Array.from(selectedIds.value)
          })

          tableRefRestHook.refresh()
        }
      })
    }

    function handleClear() {
      showConfirm({
        content: '确认清空？',
        onOk: async () => {
          await loginLogApi.clearLoginLog()

          tableRefRestHook.refresh()
        }
      })
    }

    async function handleExport() {
      const { form, pager } = tableRef.value.getProxyInfo()!

      const dto = processingData(form)

      try {
        tableRefRestHook.showLoading()

        const res = await loginLogApi.exportLoginLogPage({
          pageSize: pager.pageSize,
          pageNum: pager.currentPage,
          ...dto
        })

        download(res)
      } finally {
        tableRefRestHook.hideLoading()
      }
    }

    return {
      selectedIds,
      tableRef,
      tableConfig,
      pageHeightPx,
      handleDel,
      handleClear,
      handleExport
    }
  },
  render() {
    return (
      <div
        style={{
          height: this.pageHeightPx
        }}
      >
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbar_buttons: () => {
              return (
                <Space>
                  <Button
                    v-permission="monitor:loginlog:remove"
                    danger
                    ghost
                    disabled={this.selectedIds.size === 0}
                    onClick={this.handleDel}
                  >
                    删除
                  </Button>
                  <Button
                    v-permission="monitor:loginlog:remove"
                    danger
                    ghost
                    onClick={this.handleClear}
                  >
                    清空
                  </Button>
                  <Button
                    v-permission="monitor:loginlog:export"
                    type={'primary'}
                    ghost
                    onClick={this.handleExport}
                  >
                    导出
                  </Button>
                </Space>
              )
            },
            status: ({ row }) =>
              row.status === '1' ? (
                <Tag color={'red'}>失败</Tag>
              ) : (
                <Tag color={'blue'}>成功</Tag>
              )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
